package demo.jdbc;

import java.lang.reflect.InvocationTargetException;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import java.sql.Connection;

import java.sql.CallableStatement;

import javax.swing.SwingUtilities;

public class MainApp {
	public static void main(String[] args){
		
		try {
			SwingUtilities.invokeAndWait(new Runnable(){
				public void run(){
					DemoJTable frm = new DemoJTable();
					frm.setVisible(true);
				}
			});
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void demo2(){
String sql = "Select MaHS, HoTen, DTB from HocSinh";
		
		try {
			CallableStatement st = DataProvider.getConnection().prepareCall("{call timHocSinh(?)}");
			st.setString(1, "%V%");
			ResultSet rs = st.executeQuery();
			while(rs.next()){
				System.out.println( rs.getInt(1) + " " + rs.getString(2) +" "+ rs.getFloat(3) );
			}
			
			DataProvider.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
		public static void demo1(){
		String sql = "Select MaHS, HoTen, DTB from HocSinh";
		
		try {
			Statement st = DataProvider.getConnection().createStatement();
			ResultSet rs = st.executeQuery(sql);
			while(rs.next()){
				System.out.println( rs.getInt(1) + " " + rs.getString(2) +" "+ rs.getFloat(3) );
			}
			
			DataProvider.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class DataProvider{
	
	protected static java.sql.Connection _con;
	
	private DataProvider(){
		
	}
	
	private static void createConnection(){
		try {
			//Class.forName("com.mysql.jdbc.Driver");
			Class.forName("org.gjt.mm.mysql.Driver");
			Properties connectionInfo;
			
				connectionInfo = new Properties();
				connectionInfo.setProperty("characterEncoding", "UTF-8");
				connectionInfo.put("useUnicode", "true");
				connectionInfo.put("reconnect", "true");
				connectionInfo.setProperty("user", "root");
				connectionInfo.setProperty("password", "");
			
			_con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", connectionInfo);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws SQLException{
		if(_con == null || _con.isClosed())
			createConnection();
		
		return _con;
	}
	
	public static void closeConnection() throws SQLException {
		if(_con != null && !_con.isClosed())
			_con.close();
	}
}